#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:Zx
@file: data_utils.py
@time: 2025/7/23  10:27
# @describe:
"""
import json
import logging
import os
from datetime import datetime, date
from pathlib import Path
from config import Config


def load_data(filename):
    """从数据目录加载JSON数据"""
    try:
        file_path = Path(Config.DATA_DIR) / filename
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        logging.error(f'加载数据失败: {str(e)}', exc_info=True)
        return []


def save_data(data, filename):
    """保存数据到JSON文件"""
    try:
        file_path = Path(Config.DATA_DIR) / filename
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
        return True
    except Exception as e:
        logging.error(f'保存数据失败: {str(e)}', exc_info=True)
        return False


def init_stats_file():
    """初始化统计文件"""
    try:
        if not Config.STATS_FILE.exists():
            with open(Config.STATS_FILE, 'w', encoding='utf-8') as f:
                json.dump({
                    "total_visits": 0,
                    "daily_visits": {},
                    "last_visit_date": None
                }, f, ensure_ascii=False, indent=2)
    except Exception as e:
        logging.error(f'初始化统计文件失败: {str(e)}', exc_info=True)


def init_user_file():
    """初始化用户文件"""
    try:
        if not Config.USER_FILE.exists():
            with open(Config.USER_FILE, 'w', encoding='utf-8') as f:
                json.dump([], f, ensure_ascii=False, indent=2)
    except Exception as e:
        logging.error(f'初始化用户文件失败: {str(e)}', exc_info=True)


def update_visit_stats():
    """更新访问统计"""
    try:
        with open(Config.STATS_FILE, 'r', encoding='utf-8') as f:
            stats = json.load(f)

        today = datetime.now().strftime('%Y-%m-%d')
        stats['total_visits'] += 1
        stats['daily_visits'][today] = stats['daily_visits'].get(today, 0) + 1
        stats['last_visit_date'] = today

        with open(Config.STATS_FILE, 'w', encoding='utf-8') as f:
            json.dump(stats, f, ensure_ascii=False, indent=2)

        return stats['total_visits']
    except Exception as e:
        logging.error(f'更新访问统计失败: {str(e)}', exc_info=True)


def get_user_count():
    """获取注册用户数"""
    try:
        with open(Config.USER_FILE, 'r', encoding='utf-8') as f:
            users = json.load(f)
        return len(users)
    except Exception as e:
        logging.error(f'获取注册用户数失败: {str(e)}', exc_info=True)


def load_users():
    """加载用户数据"""
    try:
        with open(Config.USER_FILE, 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        logging.error("用户数据文件未找到")
        return []
    except json.JSONDecodeError as e:
        logging.error(f"用户数据文件格式错误: {e}")
        return []
    except Exception as e:
        logging.error(f"加载用户数据时发生未知错误: {e}")
        return []


def save_users(users):
    """保存用户数据"""
    try:
        with open(Config.USER_FILE, 'w', encoding='utf-8') as f:
            json.dump(users, f, indent=2, ensure_ascii=False)
        return True
    except Exception as e:
        logging.error(f"保存用户数据失败: {e}")
        return False


def get_next_user_id():
    """获取下一个用户ID"""
    try:
        users = load_users()
        return max(user['id'] for user in users) + 1 if users else 1
    except Exception as e:
        logging.error(f"获取下一个用户ID失败: {e}")
        return 1


def get_provinces():
    """获取省份数据"""
    file_path = Path(Config.DATA_DIR) / 'provinces.json'
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        logging.error(f'加载省份数据失败: {str(e)}')
        return []


def get_level():
    """获取难度数据"""
    file_path = Path(Config.DATA_DIR) / 'hikingLevel.json'
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        logging.error(f'加载难度数据失败: {str(e)}')
        return []


def get_blocked_ips_file():
    """获取存储被限流IP的文件路径"""
    try:
        today = datetime.now().strftime("%Y-%m-%d")
        return Config.DATA_DIR / f"blocked_ips_{today}.txt"
    except Exception as e:
        logging.error(f'获取存储被限流IP的文件路径失败: {str(e)}', exc_info=True)


def record_blocked_ip(ip: str):
    """记录被限流的IP到文件中"""
    file_path = get_blocked_ips_file()
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    try:
        if file_path.exists():
            with open(file_path, 'r') as f:
                existing_ips = [line.split(' - ')[0] for line in f.readlines()]
                if ip in existing_ips:
                    return

        with open(file_path, 'a') as f:
            f.write(f"{ip} - {timestamp}\n")
        logging.info(f"记录被限流IP: {ip} 在 {timestamp}")
    except Exception as e:
        logging.error(f"记录被限流IP失败: {e}")